import 'package:get/get.dart';
import '../model/notes_tree.dart';
import '../model/response.dart';
import '../apis/app.dart';
import '../static/custom_code.dart';

class StoryTreeController extends GetxController {
  // 故事树数据
  var storyTree = Rxn<NotesTreeVO>();
  var isLoading = false.obs;
  var hasError = false.obs;
  var errorMessage = ''.obs;
  
  // 当前选中的节点
  var selectedNode = Rxn<NotesTreeVO>();
  
  // 统计信息
  var totalNodeCount = 0.obs;
  var maxDepth = 0.obs;
  var leafNodeCount = 0.obs;

  @override
  void onInit() {
    super.onInit();
    
    // 获取传入的文章ID
    final notesId = Get.arguments as int;
    Get.log('StoryTree Controller init with notesId: $notesId');
    
    // 加载故事树数据
    loadStoryTree(notesId);
  }

  /// 加载故事树数据
  Future<void> loadStoryTree(int notesId) async {
    try {
      isLoading.value = true;
      hasError.value = false;
      errorMessage.value = '';
      
      Get.log('🌳 开始加载故事树: $notesId');
      
      HttpResponse response = await NoteApi.getNotesTree(notesId);
      
      if (response.code == StatusCode.getSuccess) {
        storyTree.value = NotesTreeVO.fromJson(response.data);
        
        // 计算统计信息
        if (storyTree.value != null) {
          totalNodeCount.value = storyTree.value!.getTotalNodeCount();
          maxDepth.value = storyTree.value!.getMaxDepth();
          leafNodeCount.value = storyTree.value!.getLeafNodes().length;
          
          Get.log('✅ 故事树加载成功');
          Get.log('   总节点数: ${totalNodeCount.value}');
          Get.log('   最大深度: ${maxDepth.value}');
          Get.log('   叶子节点数: ${leafNodeCount.value}');
        }
      } else {
        hasError.value = true;
        errorMessage.value = response.msg ?? '加载失败';
        Get.log('⚠️ 故事树加载失败: ${errorMessage.value}');
      }
    } catch (e) {
      hasError.value = true;
      errorMessage.value = '加载异常: $e';
      Get.log('❌ 故事树加载异常: $e');
    } finally {
      isLoading.value = false;
    }
  }

  /// 选择节点
  void selectNode(NotesTreeVO node) {
    selectedNode.value = node;
    Get.log('📍 选中节点: ${node.title}');
  }

  /// 跳转到文章详情（从故事树跳转，保留故事树页面在返回栈中）
  void navigateToNote(int notesId, int noteType) {
    if (noteType == 0) {
      Get.toNamed('/notes/detail/image', arguments: notesId);
    } else {
      Get.toNamed('/notes/detail/video', arguments: notesId);
    }
  }

  /// 刷新数据
  Future<void> refresh() async {
    if (storyTree.value != null) {
      await loadStoryTree(storyTree.value!.notesId);
    }
  }
}

